//
//  OauthViewController.m
//  SinaWeibo
//
//  Created by Apple on 16/8/11.
//  Copyright © 2016年 Apple. All rights reserved.
//

#import "AFNetworking.h"
#import "OauthViewController.h"
#import "AcountModel.h"


#define kClientId @"1131398645"
#define kClientScrect @"7bcfaa46fafba376eb3dbeebc35e3b67"
#define kRedirectURL @"http://weibo.com/xiawan75"
#define kAuthorizeURL @"https://api.weibo.com/oauth2/authorize"
#define kAccessTokenURL @"https://api.weibo.com/oauth2/access_token"

#define kAcountModel @"acountModel.plist"

@interface OauthViewController ()<UIWebViewDelegate>

@end

@implementation OauthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //1.创建取消按钮
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem setNavItemWithTitle:@"取消" target:self action:@selector(dismiss)];
    
    //2.加载授权页面
    [self loadOAuth];
    
}

-(void)loadOAuth{
    //1.拼接字符串
    NSString *URLstring = [NSString stringWithFormat:@"%@?client_id=%@&redirect_uri=%@",kAuthorizeURL,kClientId,kRedirectURL];
    
    //2.创建URl
    NSURL *URL = [NSURL URLWithString:URLstring];
    
    //3.创建请求
    NSURLRequest *URLRequest = [NSURLRequest requestWithURL:URL];
    
    //4.用webView加载请求的页面
    UIWebView *webView = [[UIWebView alloc]initWithFrame:self.view.frame];
    
    //设置代理
    webView.delegate=self;
    
    [webView loadRequest:URLRequest];
    
    //5.将界面显示出来
    [self.view addSubview:webView];
    
    
    
}

-(void)dismiss{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}


#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    //webView每次加载网页都会掉用这个方法。
    
    //1.获取当前访问页面的url
    NSString *requestURL = request.URL.absoluteString;
    
    //2.判断当前地址是否有code=
    
    NSRange range = [requestURL rangeOfString:@"code="];
    
    if (range.location != NSNotFound) {
        
        //1.截取代码
        NSString *code = [requestURL substringFromIndex:range.location + range.length];
        
        //2.利用截取到的code来获取AccessToken
        [self accessTokenWithCode:code];
        
        //3.停止访问
        return NO;
        
    }
    
    return YES;
    
}

//获取accessToken
-(void)accessTokenWithCode:(NSString *)code{
    
//
//    client_id	true	string	申请应用时分配的AppKey。
//    client_secret	true	string	申请应用时分配的AppSecret。
//    grant_type	true	string	请求的类型，填写authorization_code
//    
//    grant_type为authorization_code时
//    必选	类型及范围	说明
//    code	true	string	调用authorize获得的code值。
//    redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
    
    //1.封装请求数据
    NSDictionary *parameters = @{@"client_id":kClientId,
                                 @"client_secret": kClientScrect,
                                     @"grant_type": @"authorization_code",
                                     @"code": code,
                                     @"redirect_uri":kRedirectURL
                                 };
    
    
    
    
    //2.创建网络请求管理对象
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    
    //新浪只支持text/plain
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    
    
    //3.用管理对象发送post请求t
    
    [sessionManager POST:kAccessTokenURL parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"授权成功 %@",responseObject);
        
        //访问到的数据！
//        "access_token" = "2.00UzPxwBPTOZOB8dd7b014a8QeG7PE";
//        "expires_in" = 157679999;
//        "remind_in" = 157679999;
//        uid = 1787283144;
        
        //1.创建模型，将返回的字典转换为模型
        AcountModel *acountModel = [AcountModel acountModelWithDict:responseObject];
        
        //2.将模型储存起来
        [acountModel saveModel];
        
        NSLog(@"%@",NSTemporaryDirectory());
        
        //3.判断该显示新特性还是欢迎界面
        
        
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"授权失败 %@",error);
    }];
    
}

- (void)webViewDidStartLoad:(UIWebView *)webView{
    
    [SVProgressHUD showWithStatus:@"正在加载中！" ];
    
}


- (void)webViewDidFinishLoad:(UIWebView *)webView{
    
    [SVProgressHUD dismiss];
}


- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error{
    
    [SVProgressHUD dismiss];
    
}



@end
